package cn.tedu.spring.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfiguration {
    //@Autowired
    //@Qualifier("threadPoolProperties")
    private ThreadPoolProperties threadPoolProperties;//=new ThreadPoolProperties();
    @Autowired
    public ThreadPoolConfiguration(ThreadPoolProperties threadPoolProperties){
        System.out.println("ThreadPoolConfiguration()");
        this.threadPoolProperties=threadPoolProperties;
    }

    /**
     * @Bean注解描述的方法，spring中会通过反射技术去调用
     * @Bean注解没有指定名字，默认bean的名字为方法名，假如指定可以通过@Bean("bean的名称")
     */
    @Bean
    public ExecutorService threadPool(){
        System.out.println("threadPool()");
        //构建阻塞式队列(用于存储人对象)
        BlockingQueue<Runnable> blockingQueue=
                new LinkedBlockingQueue<>(threadPoolProperties.getQueueCapacity());
        //构建池对象
        return new ThreadPoolExecutor(
                threadPoolProperties.getCorePoolSize(),
                threadPoolProperties.getMaximumPoolSize(),
                threadPoolProperties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                blockingQueue);
    }

    public ThreadPoolProperties getThreadPoolProperties() {
        return threadPoolProperties;
    }
}
